package hy.controller;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Collection;

public class SolrTest {
    SolrClient c;
    @Before
    public void init(){
        String url="http://192.168.188.100:8983/solr/first";
        c=new HttpSolrClient.Builder(url).build();
    }

    @After
    public void destory()throws Exception{
        c.commit();
        c.close();
    }

    @Test
    public void insert()throws Exception{
        SolrInputDocument b=new SolrInputDocument();
        b.addField("id","4");
        b.addField("name","侠客行");
        b.addField("price","12");
        b.addField("content","石钟玉，石破天");
        c.add(b);

        b=new SolrInputDocument();
        b.addField("id","5");
        b.addField("name","天龙八部");
        b.addField("price","22");
        c.add(b);

        b=new SolrInputDocument();
        b.addField("id","6");
        b.addField("name","东游记");
        b.addField("price","10");
        c.add(b);

        b=new SolrInputDocument();
        b.addField("id","7");
        b.addField("name","三国志");
        b.addField("price","32");
        c.add(b);
    }

    @Test
    public void delete()throws Exception{
        //c.deleteById("1");
        //c.deleteByQuery("name:西");
        c.deleteByQuery("id:*");
    }

    @Test
    public void update()throws Exception{
        SolrInputDocument b=new SolrInputDocument();
        b.addField("id","1");
        b.addField("bookname","侠客岛龙的故事。。。");
        b.addField("price","112");
        c.add(b);
    }

    @Test
    public void query()throws Exception{
        //设置查询条件
        SolrQuery q=new SolrQuery();
        //q.setQuery("name:龙");
        //q.setQuery("price:22");
        //q.setQuery("name:*");
        q.setQuery("*:*");
        //指定排序字段
        q.setSort("price",SolrQuery.ORDER.desc);
        //执行查询
        QueryResponse rs=c.query(q);
        //解析查询结果
        SolrDocumentList res=rs.getResults();
        long num=res.getNumFound();
        System.out.println("数量："+num);
        for(int i=0;i<num;i++){
            SolrDocument d=res.get(i);
            Collection<String> col=d.getFieldNames();
            for(String key:col){
                System.out.println(key+":"+d.get(key));
            }
        }
    }
}